const Logger = require('../utils/logger').Logger('res-error');
const DEFAULT_ERROR_STATUS = 500;
const DEFAULT_SUCCESS_STATUS = 200;

module.exports = (req, res, next)=> {

    /**
     * 成功返回
     * @param payload   返回的数据
     */
    res.success = (payload)=> {
        return res.json({
            message: 'ok',
            timestamp: Date.now(),
            status: DEFAULT_SUCCESS_STATUS,
            payload: payload
        })
    };

    /**
     *  失败返回
     * @param error 失败返回的信息
     * @param status    失败返回的错误状态
     */
    res.error = (error, status)=> {
        let message;
        if (typeof error === 'string') {
            message = error;
        } else if ('message' in error) {
            message = error.message;
            if (error instanceof Error) {
                Logger.error('系统错误：' +
                    JSON.stringify({
                            message: error.message,
                            stack: error.stack
                        }
                    ));
            }
        }
        message = message || '系统错误';
        return res.json({
            message: message,
            status: status || DEFAULT_ERROR_STATUS,
            timestamp: Date.now()
        });
    };

    next()
};